﻿using Alipay.AopSdk.Core.Util;
using LPP.Entity.BusEntitys;
using LPP.Entity.Orders;
using LPP.Service.Payment;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LPP.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class PaymentController : ControllerBase
{
    private readonly IPaymentService _paymentService;
    private readonly ILogger<PaymentController> _logger;

    public PaymentController(
        IPaymentService paymentService,
        ILogger<PaymentController> logger)
    {
        _paymentService = paymentService ?? throw new ArgumentNullException(nameof(paymentService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    [HttpPost("alipay")]
    public async Task<IActionResult> AliPay([FromBody] PaymentRequest request)
    {
        try
        {
            if (request == null || string.IsNullOrEmpty(request.OrderId) || request.Amount <= 0)
            {
                return BadRequest(new { success = false, message = "无效的支付请求" });
            }

            var paymentUrl = await _paymentService.CreatePaymentAsync(new Order
            {
                OrderID = request.OrderId,
                Amount = request.Amount,
                PaymentMethod = PaymentMethod.Alipay
            });

            return Ok(new { success = true, url = paymentUrl });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建支付宝支付失败: {@Request}", request);
            return BadRequest(new { success = false, message = "创建支付失败" });
        }
    }

    [HttpPost("alipay/notify")]
    public async Task<IActionResult> HandleAlipayNotify([FromForm] Dictionary<string, string> parameters)
    {
        try
        {
            var result = await _paymentService.HandlePaymentNotifyAsync(parameters);
            return Ok(result ? "success" : "fail");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理支付宝通知失败: {@Parameters}", parameters);
            return BadRequest("fail");
        }
    }

    [HttpPost("wechat")]
    public async Task<IActionResult> WeChatPay([FromBody] PaymentRequest request)
    {
        try
        {
            if (request == null || string.IsNullOrEmpty(request.OrderId) || request.Amount <= 0)
            {
                return BadRequest(new { success = false, message = "无效的支付请求" });
            }

            var paymentData = await _paymentService.CreatePaymentAsync(new Order
            {
                OrderID = request.OrderId,
                Amount = request.Amount,
                PaymentMethod = PaymentMethod.WeChatPay
            });

            return Ok(new { success = true, data = paymentData });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建微信支付失败: {@Request}", request);
            return BadRequest(new { success = false, message = "创建支付失败" });
        }
    }

    [HttpPost("wechat/notify")]
    public async Task<IActionResult> HandleWeChatNotify([FromBody] Dictionary<string, string> parameters)
    {
        try
        {
            var result = await _paymentService.HandlePaymentNotifyAsync(parameters);
            return Ok(new { code = result ? "SUCCESS" : "FAIL" });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理微信支付通知失败: {@Parameters}", parameters);
            return BadRequest(new { code = "FAIL", message = "处理通知失败" });
        }
    }

    [HttpGet("verify")]
    public async Task<IActionResult> VerifyPayment([FromQuery] string orderId, [FromQuery] string tradeNo, [FromQuery] string paymentType)
    {
        try
        {
            var result = await _paymentService.VerifyPaymentAsync(orderId, tradeNo, paymentType);
            return Ok(new { success = true, verified = result });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证支付状态失败: OrderId={OrderId}, TradeNo={TradeNo}, PaymentType={PaymentType}",
                orderId, tradeNo, paymentType);
            return BadRequest(new { success = false, message = "验证支付失败" });
        }
    }
}

public class PaymentRequest
{
    public string OrderId { get; set; }
    public decimal Amount { get; set; }
}